<template>
  <div class="box">
    <el-form class="msg-info inline-form"
             :model="msgInfo"
             :rules="msgInfoRules"
             :label-width="labelWidth"
             ref="msgInfo">
      <el-form-item label="标题"
                    prop="title">
        <el-input v-model="msgInfo.title"></el-input>
      </el-form-item>
      <el-form-item label="封面图片"
                    prop="img">
        <el-upload class="avatar-uploader"
                   :action="uploadImg.action"
                   :on-remove="handleRemove"
                   :on-preview="handlePreview"
                   :on-success="handleSuccess"
                   multiple
                   :limit="1"
                   :before-upload="qwe"
                   :file-list="fileList"
                   :data="resData"
                   list-type="picture">
          <el-button size="small"
                     type="primary">点击上传</el-button>
          <div slot="tip"
               class="el-upload__tip">只能上传jpg/png文件</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="摘要"
                    prop="abstractText">
        <el-input v-model="msgInfo.abstractText"
                  type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="内容">
        <quill-editor style="width: 600px;"
                      ref="myTextEditor"
                      @change="showChange($event)"
                      v-model="msgInfo.content"
                      :options="editorOption">
        </quill-editor>
        <el-upload style="display:none"
                   :action="uploadImg.action"
                   :show-file-list="false"
                   :before-upload='newEditorbeforeupload'
                   :on-success='newEditorSuccess'
                   ref="uniqueId"
                   id="uniqueId">
        </el-upload>
        <!--
        <el-input type="hidden"
                  v-model="msgInfo.content"></el-input> -->
      </el-form-item>
      <el-form-item>
        <el-button class="pan-btn green-btn sm-btn"
                   size="small"
                   @click="saveMsgHandle">保存
        </el-button>
      </el-form-item>
    </el-form>
    <div class="phone">

    </div>
    <section class="content">
      <div class="conTitle">
        <span>&lt;</span> 文章
      </div>
      <div class="conText">
        <div>{{msgInfo.title}}</div>
        <div>{{msgInfo.abstractText}}</div>
        <div v-html="msgInfo.content"
             class="con ql-editor"></div>
      </div>
    </section>
  </div>
  </div>
</template>
<script>
import { parseTime } from '@/utils/index'
import request from '@/utils/request'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  name: 'PeriodicalEdit',
  props: ['n', 'json'],
  data() {
    return {
      uploadImg: {
        action: '/activityConsole/periodicalMessage/uploadImage/'
      },
      resData: {
        id: this.$route.query.activityId
      },
      backgroundImage: '',
      msgInfoStatus: null,
      msgInfoDate: '',
      fullUrl: '',
      fileList: [],
      list: [],
      questionnaireContentFlag: false,
      guessContentFlag: false,
      showWordLimit: true,
      // /////x信息编辑
      msgInfo: {
        title: '',
        abstractText: '',
        content: '',
        backgroundImage: ''
      },
      msgInfoRules: {
        title: [
          { required: true, trigger: 'blur', message: '请输入活动标题' }
        ],
        abstractText: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      labelWidth: '150px',
      editorOption: {
        placeholder: 'Hello World'
      },
      id: '',
      guessInfo: {
        content: '',
        baseIntegral: '',
        platformPercent: ''
      }
    }
  },
  created() {
    this.getMsgInfo()
  },
  mounted() {
    var imgHandler = async function(state) {
      if (state) {
        var fileInput = document.querySelector('#uniqueId input') // 隐藏的file元素
        console.log(fileInput)
        fileInput.click() // 触发事件
      }
    }
    this.$refs.myTextEditor.quill.getModule('toolbar').addHandler('image', imgHandler)
  },
  components: {
    quillEditor
  },
  methods: {
    newEditorbeforeupload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      if (isJPG && isLt2M) this.imageLoading = true
      return isJPG && isLt2M
    },
    // 上传图片回调
    newEditorSuccess(response, file, fileList) {
      if (response.status === '200') {
        this.addImgRange = this.$refs.myTextEditor.quill.getSelection()
        this.$refs.myTextEditor.quill.insertEmbed(this.addImgRange != null ? this.addImgRange.index : 0, 'image', '/ActivityWeb/static/' + response.data)
      }
      //   this.imageLoading = false
    },
    showChange(event) {
    },
    getMsgInfo() {
      // ////获取编辑信息
      const _this = this
      if (this.$route.query.activityId) {
        request({
          url: '/activityConsole/periodicalMessage/getMessageById/' + this.$route.query.activityId,
          method: 'get'
        }).then(res => {
          const dataObj = res
          _this.msgInfo = dataObj.data
          var obj = {}
          obj.url = '/ActivityWeb/static/' + _this.msgInfo.backgroundImage
          _this.fileList.push(obj)
          console.log(_this.fileList)
        }).catch(err => {
          console.log(err)
        })
      }
    },
    // 保存事件
    saveMsgHandle() {
      const _this = this
      if (_this.$route.query.templateId) {
        _this.msgInfo.backgroundImage = _this.fullUrl
        _this.msgInfo.templateId = _this.$route.query.templateId
        var params = _this.msgInfo
        request({
          url: '/activityConsole/periodicalMessage/addPeriodicalMessage',
          method: 'post',
          dataType: 'json',
          headers: {
            'Content-Type': 'application/json;charset=utf-8'
          },
          data: params
        }).then(res => {
          console.log(111)
          _this.$message({
            type: 'success',
            message: '保存成功'
          })
          console.log(res)
        }).catch(err => {
          console.log(222)
          _this.$message({
            type: 'error',
            message: '保存失败'
          })
          console.log(err)
        })
      } else {
        _this.msgInfo.backgroundImage = _this.fullUrl.backgroundImage
        const params1 = _this.msgInfo
        request({
          url: '/activityConsole/periodicalMessage/updatePeriodicalMessage',
          method: 'post',
          dataType: 'json',
          headers: {
            'Content-Type': 'application/json;charset=utf-8'
          },
          data: params1
        }).then(res => {
          console.log(333)
          _this.$message({
            type: 'success',
            message: '保存成功'
          })
          console.log(res)
        }).catch(err => {
          console.log(444)
          _this.$message({
            type: 'error',
            message: '保存失败'
          })
          console.log(err)
        })
      }
    },
    qwe(file) {
      const _this = this
      const b = file.type.indexOf('image') !== -1
      if (!b) {
        _this.$message({
          type: 'error',
          message: '文件类型不支持'
        })
        return false
      }
      return true
    },
    handleRemove(file, fileList) {
      const _this = this
      console.log('handleRemove:===============================================')
      _this.fileList = fileList
    },
    handlePreview(file) {
      const _this = this
      console.log('handlePreview:===============================================')
      console.log(file)
      console.log(_this.fileList)
    },
    handleSuccess(response, file, fileList) {
      const _this = this
      console.log('handlePreviewSuccess:===============================================')
      _this.fileList = fileList
      _this.fullUrl = response.data
    }
  }
}
</script>
<style scoped>
.box {
  display: flex;
  justify-content: space-around;
}

.msg-info {
  padding-top: 50px;
}

.el-input {
  position: relative;
  font-size: 14px;
  display: inline-block;
  width: 600px;
}

.el-textarea {
  width: 600px;
}

.phone {
  margin: 2.5vh 5vw;
  width: 30%;
  height: 100vh;
  overflow: hidden;
}
.content {
  position: fixed;
  width: 360px;
  height: 80%;
  bottom: 0;
  top: 100px;
  right: 6vw;
  background: url("../../assets/images/journal.png") no-repeat top center;
  background-size: 100% 100%;
}
.conText {
  width: 80%;
  margin: 0 auto 8%;
  height: 80%;
  overflow-y: scroll;
}
.conTitle {
  width: 80%;
  margin: 20% auto 2%;
  text-align: center;
}
.conTitle span {
  float: left;
}

::-webkit-scrollbar {
  display: none;
}
</style>
<style type='text/css'>
.content .conText .con.ql-editor p {
  padding: 3px 0;
}

.content .conText .con.ql-editor img {
  width: 100%;
  margin: 6px auto;
}
</style>
